package com.xincheng.shuimalong.activity.insurance;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.gson.reflect.TypeToken;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.xlog.XLog;
import com.xincheng.library.xswipemenurecyclerview.recycler.XRecyclerView;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.adapter.friend.NewFriendAdapter;
import com.xincheng.shuimalong.adapter.friend.SearchFriendAdapter;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.friend.ApplyFriendBean;
import com.xincheng.shuimalong.entity.friend.Friend;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.ShowActivity;
import com.xincheng.shuimalong.view.ListItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.ContactNotificationMessage;

import static com.xincheng.shuimalong.common.ApplyFriendCommon.CHAT;
import static com.xincheng.shuimalong.common.ApplyFriendCommon.FRIEND;
import static io.rong.message.ContactNotificationMessage.CONTACT_OPERATION_REQUEST;

/**
 * Created by 许浩 on 2017/7/18.
 */

public class SearchFriendActivity extends BaseActivity implements SearchFriendAdapter.onApplyListener {
    @BindView(R.id.search_content_et)
    EditText searchContentEt;
    @BindView(R.id.search_content_clear_iv)
    ImageView searchContentClearIv;
    @BindView(R.id.friend_recyclerview)
    XRecyclerView friendRecyclerview;
    SearchFriendAdapter adapter;
    private List<ApplyFriendBean.data> infolist;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_addfriend_layout;
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.search_friend_title));
        infolist = new ArrayList<>();
        adapter = new SearchFriendAdapter(getContext(), infolist);
        adapter.setOnApplyListener(this);
        friendRecyclerview.setLayoutManager(new LinearLayoutManager(getContext()));
        friendRecyclerview.addItemDecoration(new ListItemDecoration());
        friendRecyclerview.setAdapter(adapter);
    }

    @Override
    public void addListener() {
        searchContentEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    searchFriend(s.toString());
                } else {
                    infolist.clear();
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }

    @OnClick(R.id.search_content_clear_iv)
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_content_clear_iv:
                searchContentEt.setText("");
                break;
        }
    }

    private void searchFriend(String search) {
        RetroSubscrube.getInstance().postSubscrube(AppUrl.SEARCHUSE, PostParam.searchus(PrefUtil.getString(getContext
                        (), PrefKey.TOKEN, ""), search),
                new BaseObserver(getContext()) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        try {
                            infolist.clear();
                            List<ApplyFriendBean.data> info = GsonUtil.parseData(data, new
                                    TypeToken<List<ApplyFriendBean.data>>() {
                            }.getType());
                            infolist.addAll(info);
                            adapter.notifyDataSetChanged();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void AddFriend(final String friend_id) {
        RetroSubscrube.getInstance().postSubscrube(AppUrl.APPLY_FRIENDS,
                PostParam.applyFriends(PrefUtil.getString(getContext(), PrefKey.TOKEN, ""), friend_id, ""),
                new BaseObserver(getContext(), getString(R.string.loading_submit)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        sendNotifiMessage(friend_id, msg);
                    }
                }
        );
    }

    private void sendNotifiMessage(String friend_id, final String msg) {
        ContactNotificationMessage notificationMessage = ContactNotificationMessage.obtain(CONTACT_OPERATION_REQUEST
                , PrefUtil.getString(getContext(), PrefKey.LOGIN_USER_ID, "")
                , friend_id
                , getString(R.string.add_friend, PrefUtil.getString(getContext(), PrefKey.LOGIN_NICKNAME, "")));
        RongIMClient.getInstance().sendMessage(Conversation.ConversationType.PRIVATE,
                friend_id,
                notificationMessage,
                null,
                null,
                new IRongCallback.ISendMessageCallback() {
                    @Override
                    public void onAttached(Message message) {
                        // 消息成功存到本地数据库的回调
                    }

                    @Override
                    public void onSuccess(Message message) {
                        // 消息发送成功的回调
                        showToast(msg);
                        XLog.e("申请成功" + message.getConversationType());
                        XLog.e(message.toString());
                    }

                    @Override
                    public void onError(Message message, RongIMClient.ErrorCode errorCode) {
                        // 消息发送失败的回调
                        XLog.e(message);
                        XLog.e(errorCode);
                    }
                });
    }

    @Override
    public void onApply(ApplyFriendBean.data data, int status) {
        switch (status) {
            case FRIEND:
                AddFriend(String.valueOf(data.getUser_id()));
                break;
            case CHAT:
                RongIM.getInstance().startPrivateChat(getContext(), String.valueOf(data.getUser_id()), data
                        .getNick_name());
//                Friend.Data friend=new Friend.Data();
//                friend.setFrend_id(String.valueOf(data.getUser_id()));
//                friend.setUser_id(String.valueOf(data.getUser_id()));
//                friend.setId(String.valueOf(data.getId()));
//                friend.setFace(data.getAvatar());
//                friend.setNick_name(data.getNick_name());
//                Bundle bundle = new Bundle();
//                bundle.putSerializable(IntentKey.FRIEND_BEAN, friend);
//                ShowActivity.showActivityForResult(SearchFriendActivity.this, ChatActivity.class, bundle,
// RequestCodeKey.UP_FRIEND_LIST);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
